/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.anhndt.audiobook.business;

import com.anhndt.audiobook.iface.ProcessListener;
import com.anhndt.audiobook.utils.Util;
import com.anhndt.audiobook.utils.StringUtil;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.io.ContentConnection;

/**
 *
 * @author Anhndt
 */
public class ListLoaderTask implements Runnable {

    private String[] urls;
    protected ProcessListener listener;
    private Thread runner = null;
    protected boolean loadding;
    private int indexUrlLoaded = 0;

    public ListLoaderTask(String[] urls, ProcessListener listener) {
        this.urls = urls;
        this.listener = listener;
    }

    public boolean isLoading() {
        return loadding;
    }

    public synchronized void start() {
        try {
            loadding = true;
            if (runner == null) {
                runner = new Thread(this);
                runner.setPriority(Thread.MAX_PRIORITY);
            }
            runner.start();
        } catch (Throwable t) {
            stop();
        }
    }

    public synchronized void stop() {
        try {
            loadding = false;
            if (runner != null) {
                runner.interrupt();
                runner = null;
            }
        } catch (Exception ex) {
        }
    }

    public void setListener(ProcessListener listener) {
        this.listener = listener;
    }

//    private int getIndexUrlStart() {
//        if(isPause && indexUrlLoaded < urls.length) {
//            return indexUrlLoaded;
//        }
//        return 0;
//    }
    public boolean isFinished() {
        return indexUrlLoaded >= urls.length - 1;
    }

    public void run() {
        if (urls == null) {
            return;
        }
        for (int i = 0; i < urls.length; i++) {
            try {
                load(i);
            } catch (Throwable e) {
                System.gc();
                continue;
            }
        }
        stop();
        loadding = false;
    }

    public void load(int i) throws OutOfMemoryError, IOException, InterruptedException {
        byte[] audioData = getData(i);
        if (audioData != null && listener != null) {
            listener.onSuccess(audioData, i);
        } else {
            listener.onError("Have Exception in download url : " + urls[i], i);
        }
    }

    public byte[] getData(int i) throws IOException {
        String url = Util.getUrl(urls[i]);
        if (StringUtil.isNullOrEmpty(url)) {
            return null;
        }
//        System.out.println(" ------------------ START  [Downloading] " + url);
        ContentConnection connection = null;
        // * There is a bug in MIDP 1.0.3 in which read() sometimes returns
        //   an invalid length. To work around this, I have changed the
        //   stream to DataInputStream and called readFully() instead of read()
        DataInputStream iStrm = null;
        ByteArrayOutputStream bStrm = null;
        byte data[] = null;
        try {
            connection = (ContentConnection) Connector.open(url);
            iStrm = connection.openDataInputStream();
            // ContentConnection includes a length method

            int length = (int) connection.getLength();
            if (length != -1) {
//                System.out.println("readFully  [" + url + "]" + "    lenght = " + length);
                data = new byte[length];
                iStrm.readFully(data);
            } else // Length not available...
            {
                bStrm = new ByteArrayOutputStream();
                int ch;
                while ((ch = iStrm.read()) != -1) {
                    if (!loadding) {
                        System.out.println("ko load anh nua");
                        data = null;
                        return null;
                    }
                    bStrm.write(ch);
                }
                data = bStrm.toByteArray();
//                System.out.println(" ------------------ START  [SUCCESSFUL] " + data.length + "  -- " + url );
            }
            if (data != null) {
                indexUrlLoaded = i;
                int lenght = data.length / 1024;
                Util.incrementData(lenght);
            }
            return data;
        } catch (Exception e) {
        } finally {

            // Clean up
            if (iStrm != null) {
                iStrm.close();
            }
            if (connection != null) {
                connection.close();
            }
            if (bStrm != null) {
                bStrm.close();
            }
        }
        return data;
    }
}
